import java.io.*;
import java.sql.*;
import dbBean.DBConnectionManager;

public class GoogleGPS_SMS {
  public static void main(String[] args) {
  String texto="", line=null, user, telefono=null;
  String[] tokens;

  try {
    BufferedReader f=new BufferedReader(new FileReader(args[0]));
    while((line=f.readLine()).length()>0) {
	if(line.startsWith("From: ")) {
	  int i=line.indexOf(' ');
	  telefono=line.substring(i+1);
	}
    }

    while((line=f.readLine())!=null)
	texto+=line+"\n";

    f.close();
  } catch(IOException e) {
    e.printStackTrace();
    System.exit(1);
  }

  tokens=texto.split(" +");

  if((tokens[0].compareToIgnoreCase("ALTA")==0) &&(tokens.length>1)) {
    DBConnectionManager connMgr=DBConnectionManager.getInstance();
    Connection conn=null;
    try {
	user=tokens[1].trim();


	conn=connMgr.getConnection("mysql");
        PreparedStatement pstmt=conn.prepareStatement("SELECT telefono FROM usuarios WHERE user=?;");
	pstmt.setString(1, user);
	ResultSet rs=pstmt.executeQuery();
	if(rs.next()) {
	  if(rs.getString(1)==null) {
	    pstmt.close();
            pstmt=conn.prepareStatement("UPDATE usuarios SET telefono=? WHERE user=?;");
	    pstmt.setString(1, telefono);
	    pstmt.setString(2, user);
	    pstmt.executeUpdate();
          }
  	}
	rs.close();
	pstmt.close();
        connMgr.freeConnection("mysql",conn);
    } catch(SQLException e) {
	e.printStackTrace();
    }

    if(conn!=null)
        connMgr.freeConnection("mysql",conn);
  }
}
}
